package com.itedge.infrastructure.util;

import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.itedge.infrastructure.domain.IEntity;

/**
 * Class containing common-helpers for server-side views preparations and processing.
 * 
 * @author jhe
 *
 */
public class WebUtil {
	
	/**
	 * Concates all items from collection to their string representations (by calling object toString() method),
	 * delimiting them with comma.
	 * 
	 * @param c
	 * @return string representation of all objects, delimited with comma
	 */
    public static String getStringFromCollection(Collection<? extends Object> c) {
    	StringBuffer s = new StringBuffer();
    	Iterator<? extends Object> it = c.iterator();
    	while (it.hasNext()) {
    		s.append(it.next().toString());
    		if (it.hasNext()) {
    			s.append(",");
    		}
    	}
    	return s.toString();
    }
    
    /**
     * Concates all ID properties from persistent entities into string, delimiting them with comma.
     * 
     * @param c
     * @return string representation of all entity id's, delimited with comma
     */
    public static String getIdsStringFromEntities(Collection<? extends IEntity> c) {
    	StringBuffer s = new StringBuffer();
    	Iterator<? extends IEntity> it = c.iterator();
    	while (it.hasNext()) {
    		s.append(it.next().getId());
    		if (it.hasNext()) {
    			s.append(",");
    		}
    	}
    	return s.toString();    	
    }
    
    /**
     * Encodes url path segment with default encoding.
     * 
     * @param pathSegment
     * @param request
     * @return encoded path segment
     */
    public static String encodeUrlPathSegment(String pathSegment, HttpServletRequest request) {
        String enc = request.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        }
        catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }    
}

